package com.jiawa.train.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiawa.train.business.domain.po.SkToken;
import com.jiawa.train.business.mapper.SkTokenMapper;
import com.jiawa.train.business.req.SkTokenQueryReq;
import com.jiawa.train.business.req.SkTokenSaveReq;
import com.jiawa.train.business.resp.SkTokenQueryResp;
import com.jiawa.train.business.service.IDailyTrainSeatService;
import com.jiawa.train.business.service.IDailyTrainStationService;
import com.jiawa.train.business.service.ISkTokenService;
import com.jiawa.train.common.resp.PageResp;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 秒杀令牌 服务实现类
 * </p>
 *
 * @author hrz
 * @since 2025-09-10
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SkTokenServiceImpl extends ServiceImpl<SkTokenMapper, SkToken> implements ISkTokenService {

    private final IDailyTrainSeatService dailyTrainSeatService;
    private final IDailyTrainStationService dailyTrainStationService;

    /**
     * 初始化
     */
    @Override
    public void genDaily(Date date, String trainCode) {
        log.info("删除日期【{}】车次【{}】的令牌记录", DateUtil.formatDate(date), trainCode);
        this.lambdaUpdate()
                .eq(SkToken::getTrainCode, trainCode)
                .eq(SkToken::getDate, date)
                .remove();

        LocalDateTime now = LocalDateTime.now();
        SkToken skToken = new SkToken();
        skToken.setDate(date);
        skToken.setTrainCode(trainCode);
        skToken.setCreateTime(now);
        skToken.setUpdateTime(now);

        int seatCount = dailyTrainSeatService.countSeat(date, trainCode);
        log.info("车次【{}】座位数：{}", trainCode, seatCount);

        long stationCount = dailyTrainStationService.countByTrainCode(date, trainCode);
        log.info("车次【{}】到站数：{}", trainCode, stationCount);

        // 3/4需要根据实际卖票比例来定，一趟火车最多可以卖（seatCount * stationCount）张火车票
        int count = (int) (seatCount * stationCount); // * 3/4);
        log.info("车次【{}】初始生成令牌数：{}", trainCode, count);
        skToken.setCount(count);

        this.save(skToken);
    }

    @Override
    public void save(SkTokenSaveReq req) {
        LocalDateTime now = LocalDateTime.now();
        SkToken skToken = BeanUtil.copyProperties(req, SkToken.class);
        if (ObjectUtil.isNull(skToken.getId())) {
            skToken.setCreateTime(now);
            skToken.setUpdateTime(now);
            this.save(skToken);
        } else {
            skToken.setUpdateTime(now);
            this.updateById(skToken);
        }
    }

    @Override
    public PageResp<SkTokenQueryResp> queryList(SkTokenQueryReq req) {
        log.info("查询页码：{}", req.getPage());
        log.info("每页条数：{}", req.getSize());
        Page<SkToken> page = this.lambdaQuery()
                .orderByDesc(SkToken::getId)
                .page(new Page<>(req.getPage(), req.getSize()));
        log.info("总行数：{}", page.getTotal());
        log.info("总页数：{}", page.getPages());
        List<SkToken> records = page.getRecords();
        List<SkTokenQueryResp> list = BeanUtil.copyToList(records, SkTokenQueryResp.class);
        PageResp<SkTokenQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(page.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    @Override
    public void delete(Long id) {
        this.removeById(id);
    }
}
